package com.inspur.attendance.Service.ServiceImpl;


import com.inspur.attendance.Dao.DepartmentDao;
import com.inspur.attendance.Dao.UserDao;
import com.inspur.attendance.Entity.Department;
import com.inspur.attendance.Entity.User;
import com.inspur.attendance.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    DepartmentDao departmentDao;

    @Override
    public Page<User> getPage(int pageNo, int pageSize) throws Exception {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by("id").descending());
        return userDao.findAll(pageable);
    }

    @Transactional
    @Override
    public boolean delUser(Long id) {
        try {
            departmentDao.delUserTotal((userDao.findTopById(id)).getDepartmentId());
            userDao.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<User> findUserByName(String name) throws Exception {
        return userDao.findUsersByNameLike("%"+name+"%");
    }

    @Override
    public List<Department> getDepartmentId() throws Exception {
        return departmentDao.findAll();
    }


    @Override
    public void saveUser(User user){
        try {
            userDao.save(user);
            departmentDao.addUserTotal(user.getDepartmentId());
        } catch (Exception e) {
            throw e;
        }

    }

    @Transactional
    @Modifying
    @Override
    public void editUser(User user, String departmentId) {
        try {
            userDao.save(user);
        }catch (Exception e) {
            throw e;
        }
    }

    @Override
    public List<User> findAll() throws Exception {
        return userDao.findAll();
    }

    @Override
    public User findByAccount(String account) throws Exception {
        return userDao.findTopByAccount(account);
    }
}
